<template>
    <div style=" position: relative;"><el-card>
            <template #header>
                <!-- 搜索 -->
                <div class="checkPointIds_change_scc">
                    <el-select filterable v-if='role_off'  popper-class="xiala_css" @change="checkPointIds_change" collapse-tags collapse-tags-tooltip multiple clearable
                        v-model="checkPointIds" placeholder="请选择客户" style="width: 260px">
                        <template #header>
                            <el-checkbox v-model="checkAll" :indeterminate="indeterminate" @change="handleCheckAll">
                                全选
                            </el-checkbox>
                        </template>
                        <el-option v-for="item in getCustomerList_list" :key="item.id" :label="item.customerName"
                            :value="item.id" />
                    </el-select>
                    <el-select filterable  popper-class="xiala_css" @change="getPipeLineListByCusId_change" collapse-tags collapse-tags-tooltip multiple
                        clearable v-model="getPipeLineListByCusId_value" placeholder="请选择管线"
                        style="width: 260px;margin-left:15px;">
                        <template #header>
                            <el-checkbox v-model="checkAll2" :indeterminate="indeterminate2" @change="handleCheckAll2">
                                全选
                            </el-checkbox>
                        </template>
                        <el-option v-for="item in getPipeLineListByCusId_list" :key="item.id" :label="item.pipeLineName"
                            :value="item.id" />
                    </el-select>
                    <el-select filterable  popper-class="xiala_css" collapse-tags collapse-tags-tooltip multiple clearable
                        v-model="getCheckPointListByLineId_value" placeholder="请选择监测点"
                        style="width: 260px;margin-left:15px;">
                        <template #header>
                            <el-checkbox v-model="checkAll3" :indeterminate="indeterminate3" @change="handleCheckAll3">
                                全选
                            </el-checkbox>
                        </template>
                        <el-option v-for="item in getCheckPointListByLineId_list" :key="item.id"
                            :label="item.checkPointName" :value="item.id" />
                    </el-select>

                    <el-select  popper-class="xiala_css" @change="handleCheckAll4" v-model="find_data.rules" placeholder="请选择防盗报警类型"
                        style="width: 200px;margin-left:15px;">
                        <el-option label="--请选择防盗报警类型--" value="0" />
                        <el-option label="震动报警" value="1" />
                        <el-option label="主电池报警" value="2" />
                    </el-select>

                    <el-date-picker popper-class="time_css"  style="width: 340px;margin-left:15px;" v-model="details_time" type="datetimerange"
                        start-placeholder="开始时间(采样)" end-placeholder="结束时间(采样)" format="YYYY-MM-DD HH:mm:ss"
                        value-format="YYYY-MM-DD HH:mm:ss" />
                    <el-button style="margin-left: 20px;height:30px" @click="search_btn" type="primary"
                        icon="Search">搜索</el-button>
                </div>
                <!-- 功能按钮 -->
                <div class="del_btn_Css">
                    <el-button @click="out_btn" type="warning" icon="Promotion">导出</el-button>

                </div>
            </template>
            <div>
                <el-table class="list_data_Css" border @selection-change="selection_change_btn" height="63vh"
                    ref="multipleTableRef" :data="list_data">
                    <el-table-column type="selection" width="35" />
                    <el-table-column label="编号" width="55" fixed type="index" />
                    <template v-for="item in table_data_list" :key="item.name">
                        <el-table-column v-if="item.enablePinning" :width="item.minWidth" :prop="item.name"
                            :label="item.displayName">
                            <template v-if="item.name == 'gps'" #="{ row, column, $index }">
                                <span>{{ row.gps == '1' ? '锁定' : '失锁' }}</span>
                            </template>
                            <template v-if="item.name == 'relay'" #="{ row, column, $index }">
                                <span>{{ row.relay == '1' ? '通' : '断' }}</span>
                            </template>
                            <template v-if="item.name == 'rules'" #="{ row, column, $index }">
                                <span>{{ row.pulsatorAlarm == '1' && row.batteryAlarm != '1' ? '震动报警' : row.pulsatorAlarm !=
                                    '1' && row.batteryAlarm == '1' ? '主电池报警' : row.pulsatorAlarm == '1' && row.batteryAlarm
                                        == '1' ? '震动报警/主电池报警' : '正常' }}</span>

                            </template>
                        </el-table-column>
                    </template>
                </el-table>
            </div>

            <div class="current_change_btn_css">
                <el-pagination @current-change="current_change_btn" @size-change="size_change_btn"
                    v-model:current-page="find_data.pageNo" v-model:page-size="find_data.pageSize"
                    :page-sizes="[20, 50, 100, 200, 500]" :background="true" layout="prev, pager, next, jumper,->,sizes,total,"
                    :total="total" />
            </div>
        </el-card>
    </div>

    <!-- 弹窗 -->
    <div>


    </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, watch, nextTick, markRaw } from 'vue'
import {
    getCustomerList, getPipeLineListByCusId, getCheckPointListByLineId, getSynSatelliteListByPage, importSynSatellite

} from '@/api/data_monitor.js'
import { ElMessage, ElLoading, ElMessageBox } from 'element-plus'
import { downFiles, } from '@/utils/common.js'

import CircularJSON from 'circular-json'
onMounted(async () => {
    let list_of_synchronous_satellite_data = JSON.parse(localStorage.getItem('list_of_synchronous_satellite_data'))
    if (list_of_synchronous_satellite_data) {

        nuv_off.value = true
        await getCustomerList_api()

        await role_api()
    } else {
        await getCustomerList_api()
      
        await role_api()
    }



})
let nuv_off = ref(false)
//#region 登录角色判断 
//    
let role_off = ref(true)
let role_id = ref('')
let role_customerId = ref('')
const role_api = () =>{
    let luser = JSON.parse(localStorage.getItem('luser'))
    if (luser.loginName != 'admin') {
        role_off.value = false
        role_id.value = luser.id
        role_customerId.value = luser.customerId
        checkPointIds.value = []
        checkPointIds.value.push(role_customerId.value)
        getCustomerList_list.value = []
        getCustomerList_list.value.push(role_customerId.value)
    }
}
// #endregion

const data_list = ref([''])

//#region 搜索
//#region 客户
const getCustomerList_list = ref([])
const checkPointIds = ref([])
const checkAll = ref(false)
const indeterminate = ref(false)
watch(checkPointIds, (val) => {
    getPipeLineListByCusId_value.value = []
    getCheckPointListByLineId_value.value = []
    if (val.length === 0) {
        checkAll.value = false
        indeterminate.value = false
    } else if (val.length === getCustomerList_list.value.length) {
        checkAll.value = true
        indeterminate.value = false
    } else {
        indeterminate.value = true
    }
})
const handleCheckAll = async (val) => {
    getPipeLineListByCusId_value.value = []
    getCheckPointListByLineId_value.value = []
    indeterminate.value = false
    if (val) {
        checkPointIds.value = getCustomerList_list.value.map((_) => _.id)

    } else {
        checkPointIds.value = []
    }
    getCustomerList_api()
}
const checkPointIds_change = async (e) => {
    getPipeLineListByCusId_api()
}
const getCustomerList_api = () => {
    getPipeLineListByCusId_value.value = []
    getCheckPointListByLineId_value.value = []
    getCustomerList({}).then(res => {
        if (res.resultStatus.resultCode == '0000') {
            getCustomerList_list.value = res.value
            setTimeout(() => {
                if (nuv_off.value) {
                    console.log(1)
                    let list_of_synchronous_satellite_data = JSON.parse(localStorage.getItem('list_of_synchronous_satellite_data'))
                    checkPointIds.value = list_of_synchronous_satellite_data.customerIds
                }
                getPipeLineListByCusId_api()
            }, 500)

        } else {
            return ElMessage({
                message: res.resultStatus.resultMessage,
                type: 'warning',
            })
        }

    })
}
//#endregion

//#region 管线
const getPipeLineListByCusId_list = ref([])
const getPipeLineListByCusId_value = ref([])
const checkAll2 = ref(false)
const indeterminate2 = ref(false)
watch(getPipeLineListByCusId_value, (val) => {
    getCheckPointListByLineId_value.value = []
    if (val.length === 0) {
        checkAll2.value = false
        indeterminate2.value = false
    } else if (val.length === getPipeLineListByCusId_list.value.length) {
        checkAll2.value = true
        indeterminate2.value = false
    } else {
        indeterminate2.value = true
    }
})
const handleCheckAll2 = (val) => {
    getCheckPointListByLineId_value.value = []
    indeterminate2.value = false
    if (val) {
        getPipeLineListByCusId_value.value = getPipeLineListByCusId_list.value.map((_) => _.id)

    } else {
        getPipeLineListByCusId_value.value = []
    }
    getCheckPointListByLineId_api()
}
const getPipeLineListByCusId_change = async (e) => {
    await getCheckPointListByLineId_api()
}
const getPipeLineListByCusId_api = () => {
    getCheckPointListByLineId_value.value = []
    getPipeLineListByCusId(checkPointIds.value.length > 0 ? checkPointIds.value : data_list.value).then(res => {
        if (res.resultStatus.resultCode == '0000') {
            getPipeLineListByCusId_list.value = res.value
            if (nuv_off.value) {

let list_of_synchronous_satellite_data = JSON.parse(localStorage.getItem('list_of_synchronous_satellite_data'))
getPipeLineListByCusId_value.value = list_of_synchronous_satellite_data.pipeLineIds


}
            getCheckPointListByLineId_api()

        } else {
            return ElMessage({
                message: res.resultStatus.resultMessage,
                type: 'warning',
            })
        }

    })
}
//#endregion

//#region 监测点
const getCheckPointListByLineId_value = ref([])
const getCheckPointListByLineId_list = ref([])
const checkAll3 = ref(false)
const indeterminate3 = ref(false)
watch(getCheckPointListByLineId_value, (val) => {
    if (val.length === 0) {
        checkAll3.value = false
        indeterminate3.value = false
    } else if (val.length === getCheckPointListByLineId_list.value.length) {
        checkAll3.value = true
        indeterminate3.value = false
    } else {
        indeterminate3.value = true
    }
})
const handleCheckAll3 = (val) => {
    indeterminate3.value = false
    if (val) {
        getCheckPointListByLineId_value.value = getCheckPointListByLineId_list.value.map((_) => _.id)

    } else {
        getCheckPointListByLineId_value.value = []
    }
}
const getCheckPointListByLineId_api = () => {
    let ps = {
        deviceType: '1',
        ids: getPipeLineListByCusId_value.value.length > 0 ? getPipeLineListByCusId_value.value : data_list.value
    }



    getCheckPointListByLineId(ps).then(res => {

        if (res.resultStatus.resultCode == '0000') {
            getCheckPointListByLineId_list.value = res.value

            if (nuv_off.value) {
                let list_of_synchronous_satellite_data = JSON.parse(localStorage.getItem('list_of_synchronous_satellite_data'))
                getCheckPointListByLineId_value.value = list_of_synchronous_satellite_data.checkPoints
                details_time.value[1] = list_of_synchronous_satellite_data.endTime

                details_time.value[0] = list_of_synchronous_satellite_data.startTime
                details_time.value = [list_of_synchronous_satellite_data.startTime, list_of_synchronous_satellite_data.endTime]
               find_data.rules = list_of_synchronous_satellite_data.rules
                nuv_off.value = false
                list_api()
            }

        } else {
            return ElMessage({
                message: res.resultStatus.resultMessage,
                type: 'warning',
            })
        }

    })
}
//#endregion


//#region 时间


const details_time = ref([])
//#endregion

//#region 防盗报警类型
const handleCheckAll4 = () => {
    list_api()
}
//#endregion

const search_btn = () => {

    list_api()
}

//#endregion

//#region 分页列表
const list_data = ref([])
const find_data = reactive({
    pageNo: 1,
    pageSize: 20,
    checkPoints: [],
    customerIds: [],
    pipeLineIds: [],
    startTime: "",
    endTime: "",
    rules: '0',

})
const total = ref(0)

// 分页器一夜显示多少数据页面
const size_change_btn = () => {
    find_data.pageNo = 1
    list_api()
}

// 分页器跳转页面
const current_change_btn = () => {
    list_api()
}

const list_api = () => {
    if (checkPointIds.value.length <= 0) {
        return ElMessage({
            message: '请选择客户！',
            type: 'warning',
        })
    } else if (getPipeLineListByCusId_value.value.length <= 0) {
        console.log(1,getPipeLineListByCusId_value.value)
        return ElMessage({
            message: '请选择管线！',
            type: 'warning',
        })
    } else if (getCheckPointListByLineId_value.value.length <= 0) {
        console.log(2,getCheckPointListByLineId_value.value)
        return ElMessage({
            message: '请选择监测点！',
            type: 'warning',
        })
    } else if (!details_time.value) {
        return ElMessage({
            message: '请选择时间！',
            type: 'warning',
        })
    }
    const loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(0, 0, 0, 0.7)',
  })
    find_data.checkPoints = getCheckPointListByLineId_value.value
    find_data.customerIds = checkPointIds.value
    find_data.pipeLineIds = getPipeLineListByCusId_value.value
    if (details_time.value) {
        find_data.startTime = details_time.value[0]
        find_data.endTime = details_time.value[1]
    } else {
        find_data.startTime = ''
        find_data.endTime = ''
    }
    // localStorage.setItem('list_of_synchronous_satellite_data', CircularJSON.stringify(find_data))
    getSynSatelliteListByPage(find_data).then(res => {
        loading.close()
        if (res.resultStatus.resultCode == '0000') {
            list_data.value = res.value.list
            total.value = res.value.total
        } else {
            return ElMessage({
                message: res.resultStatus.resultMessage,
                type: 'warning',
            })
        }

    })
}
//#endregion

//#region 表格数据处理
const table_data_list = reactive([
    { name: 'terminalNumber', displayName: '终端编号', minWidth: 150, enablePinning: true },
    { name: 'terminalName', displayName: '终端名称', minWidth: 200, enablePinning: true },
    { name: 'sampTime', displayName: '采样时间', minWidth: 200, enablePinning: true },
    { name: 'rules', displayName: '报警类型', minWidth: 200, enablePinning: true },
    { name: 'batVoltage', displayName: '电池电压/V', minWidth: 140, enablePinning: true },
    { name: 'polVoltage', displayName: '极化电压/V', minWidth: 140, enablePinning: true },
    { name: 'directCurrent', displayName: '直流电流/mA', minWidth: 140, enablePinning: true },
    { name: 'directCurrentDensity', displayName: '直流电流密度/A/m²', minWidth: 180, enablePinning: true },
    { name: 'exchangeCurrent', displayName: '交流杂散电流/mA', minWidth: 180, enablePinning: true },
    { name: 'exchangeCurrentDensity', displayName: '交流电流密度/A/m²', minWidth: 180, enablePinning: true },
    { name: 'gps', displayName: 'gps状态', minWidth: 100, enablePinning: true },
    { name: 'relay', displayName: '继电器状态', minWidth: 100, enablePinning: true },
    { name: 'longitude', displayName: '经度', minWidth: 100, enablePinning: true },
    { name: 'latitude', displayName: '纬度', minWidth: 100, enablePinning: true },
    { name: 'displaceAlarm', displayName: '移动告警', minWidth: 150, enablePinning: true },
])




//#endregion

//#region 表格选择
const table_list = ref([])
const selection_change_btn = (e) => {
    table_list.value = e
    console.log(e)
}
//#endregion

//#region 导出
const out_btn = () => {

    if (checkPointIds.value.length <= 0) {
        return ElMessage({
            message: '请选择客户！',
            type: 'warning',
        })
    } else if (getPipeLineListByCusId_value.value.length <= 0) {
        console.log(1,getPipeLineListByCusId_value.value)
        return ElMessage({
            message: '请选择管线！',
            type: 'warning',
        })
    } else if (getCheckPointListByLineId_value.value.length <= 0) {
        console.log(2,getCheckPointListByLineId_value.value)
        return ElMessage({
            message: '请选择监测点！',
            type: 'warning',
        })
    } else if (!details_time.value) {
        return ElMessage({
            message: '请选择时间！',
            type: 'warning',
        })
    }

    let thName = []
    for (let i = 0; i < table_data_list.length; i++) {
        if (table_data_list[i].enablePinning == true) {
            thName.push(table_data_list[i].displayName)
        }

    }

    let ps = {
        checkPoints: getCheckPointListByLineId_value.value,
        customerIds: checkPointIds.value,
        pipeLineIds: getPipeLineListByCusId_value.value,
        startTime: '',
        endTime: '',
        rules: find_data.rules,
        thName: '',
    }
    ps.thName = thName.join(',');
    if (details_time.value) {
        if (details_time.value.length > 0) {

            ps.startTime = details_time.value[0]
            ps.endTime = details_time.value[1]
        } else {

            ps.startTime = ''
            ps.endTime = ''
        }
    } else {
        ps.startTime = ''
        ps.endTime = ''
    }
    const loading = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
    })

    importSynSatellite(ps).then(res => {
        downFiles(res, '同步卫星数据')
        loading.close()


    })


}
//#endregion

</script>

<style scoped lang='scss'>

    .del_btn_Css {
        margin-top: 10px;
    }

    .list_data_Css {
        width: 100%
    }

    .current_change_btn_css {
        margin-top: 20px
    }




.map_input {
    width: 100%;
    position: relative;
    z-index: 1;
    display: flex;
    justify-content: center;

}

.div_bg:hover {
    background-color: darkgray;
}
</style>
<style>

.col-items::-webkit-scrollbar {
    width: 5px !important;
}

.col-items>label {
    margin-left: 0px !important;
    margin-top: 5px;
    width: 100%;
}
</style>
